//
//  MLPhotoView.m
//  BrowsePictureDemo
//
//  Created by GZMLUser on 14-11-13.
//  Copyright (c) 2014年 GZMLUser. All rights reserved.
//

#import "MLPhotoView.h"
#import "UIImageView+MLWebCache.h"
#import "MLPhotoInfo.h"
#import "MLPhotoLoadingView.h"

#define ZOOM_FACTOR 2.0f
#define CONTENT_INSET 4.0f
#define ZOOM_MAXIMUM 16.0f
@interface MLPhotoView ()
{
    BOOL _doubleTap; // 是否双击
    UIImageView *_imageView;
    MLPhotoLoadingView *_photoLoadingView;
}
@end

@implementation MLPhotoView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.clipsToBounds = YES; // 子控件适应当前View
        // 图片
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:_imageView];
        
        // 进度条
        _photoLoadingView = [[MLPhotoLoadingView alloc] init];
        
        // 属性
        self.scrollsToTop = NO;
        self.delaysContentTouches = NO;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.contentMode = UIViewContentModeRedraw;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES;
        self.autoresizesSubviews = NO;
        self.bouncesZoom = NO;
        self.delegate = self;
        
        // 监听点击
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        doubleTap.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTap];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        singleTap.delaysTouchesBegan = YES;
        singleTap.numberOfTapsRequired = 1;
        [self addGestureRecognizer:singleTap];
        
        //这行很关键，意思是只有当没有检测到doubleTap 或者 检测doubleTap失败，singleTap才有效
        [singleTap requireGestureRecognizerToFail:doubleTap];
    }
    return self;
}

#pragma mark -设置图片
- (void)setPhotos:(MLPhotoInfo *)photos
{
    _photos = photos;
    
    _loadType = [self selectLoadMethod:photos];
    [self showImage];
}

#pragma mark -显示图片
- (void)showImage
{
    if (_loadType == localeLoad ) { // 本地方式
        __unsafe_unretained MLPhotoInfo *photo = _photos;
        UIImage *image = nil;
       
        if (_photos.photo.image) {
            image = _photos.photo.image;
        } else {
            image = [UIImage imageWithContentsOfFile:_photos.photo.path];
            photo.photo.image = image;
        }
        _imageView.image = image;
  
    } else if (_loadType == netWorkLoad) {
        
        if (_photos.firstShow) { // 首次显示
            _imageView.image = _photos.photo.placeholder;// 站位图片
        
            // 不是gif，就马上开始下载
            if (![_photos.photo.url.absoluteString hasSuffix:@"gif"]) {
                __unsafe_unretained MLPhotoView *photoView = self;
                __unsafe_unretained MLPhotoInfo *photo = _photos;
                
                [_imageView sd_setImageWithURL:_photos.photo.url placeholderImage:_photos.photo.placeholder options:SDWebImageRetryFailed|SDWebImageLowPriority completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    photo.image = image;
                    
                    // 调整frame参数
                    [photoView adjustFrame];
                }];
            }
        }else {
            [self photoStartLoad];
        }
    }
    // 调整frame参数
    [self adjustFrame];
}

#pragma mark 选取下载方式
- (loadType)selectLoadMethod:(MLPhotoInfo *)photoInfo
{
    if (photoInfo.photo.path != nil || photoInfo.photo.image != nil) {
        return localeLoad;
    } else if (photoInfo.photo.url != nil){
        
        return netWorkLoad;
        
    } else {
        UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"提示" message:@"加载的图片不存在" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [av show];
        
        return 0;
    }
}

#pragma mark -开始加载图片
- (void)photoStartLoad
{
    if (_photos.photo.image) {
        self.scrollEnabled = YES;
        _imageView.image = _photos.photo.image;
    } else {
        self.scrollEnabled = NO;
        
        // 显示进度条 加载图片
        [_photoLoadingView showLoading];
        [self addSubview:_photoLoadingView];
        
        __unsafe_unretained MLPhotoView *photoView = self;
        __unsafe_unretained MLPhotoLoadingView *loading = _photoLoadingView;
    
        [_imageView sd_setImageWithURL:_photos.photo.url placeholderImage:_photos.photo.placeholder options:SDWebImageRetryFailed|SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            // 加载进度
            if (receivedSize > kMinProgress) {
                loading.progress = (float)receivedSize/expectedSize;
            }
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
             [photoView photoDidFinishLoadWithImage:image];
        }];
        
    }
}

#pragma mark 加载完毕
- (void)photoDidFinishLoadWithImage:(UIImage *)image
{
    if (image) {
        self.scrollEnabled = YES;
        _photos.photo.image = image;
        [_photoLoadingView removeFromSuperview];
        
        if ([self.photoViewDelegate respondsToSelector:@selector(photoViewImageFinishLoad:)]) {
            [self.photoViewDelegate photoViewImageFinishLoad:self];
        }
    } else {
        [self addSubview:_photoLoadingView];
        [_photoLoadingView showFailure]; // 下载失败
    }
    
    // 设置缩放比例
    [self adjustFrame];
}


#pragma mark -调整位置
- (void)adjustFrame
{
    if (_imageView.image == nil) return;
    
    // 基本尺寸参数
    CGSize boundsSize = self.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize imageSize = _imageView.image.size;
    CGFloat imageWidth = imageSize.width;
    CGFloat imageHeight = imageSize.height;
    
    // 设置伸缩比例
    CGFloat minScale = boundsWidth / imageWidth;
    if (minScale > 1) {
        minScale = 1.0;
    }
    CGFloat maxScale = 2.5;
    if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
        maxScale = maxScale / [[UIScreen mainScreen] scale];
    }
    self.maximumZoomScale = maxScale;
    self.minimumZoomScale = minScale;
    self.zoomScale = minScale;
    
    CGRect imageFrame = CGRectMake(0, 0, boundsWidth, imageHeight * boundsWidth / imageWidth);
    // 内容尺寸
    self.contentSize = CGSizeMake(0, boundsHeight);
    // y值
    if (imageFrame.size.height < boundsHeight) {
        imageFrame.origin.y = floorf((boundsHeight - imageFrame.size.height) / 2.0);
    } else {
        imageFrame.origin.y = 0;
    }
    
    if (_photos.firstShow) { // 第一次显示的图片
        _photos.firstShow = NO;
        if (!CGRectIsEmpty( _photos.photo.rect)) {
            _imageView.frame = [self convertRect:_photos.photo.rect toView:nil]; ;
        }
        [UIView animateWithDuration:0.3 animations:^{
            _imageView.frame = imageFrame;
        } completion:^(BOOL finished) {
            [self photoStartLoad];
        }];
        
    } else {
        _imageView.frame = imageFrame;
    }
}

#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    // 图片居中显示
    [self setImageViewCenter];
    
}
#pragma mark 设置图片居中
- (void)setImageViewCenter
{
    CGFloat offsetX = (self.bounds.size.width > self.contentSize.width)?(self.bounds.size.width - self.contentSize.width)/2 : 0.0;
    CGFloat offsetY = (self.bounds.size.height > self.contentSize.height)?(self.bounds.size.height - self.contentSize.height)/2 : 0.0;
    _imageView.center = CGPointMake(self.contentSize.width/2 + offsetX,self.contentSize.height/2 + offsetY);
}

#pragma  mark 手势处理
- (void)handleSingleTap:(UIGestureRecognizer *)tap // 单机处理
{
    _doubleTap = NO;
    
    if (!CGRectIsEmpty(_photos.photo.rect)) { // 外面点击的图片
        [self performSelector:@selector(hideCurrent) withObject:nil afterDelay:0.2];
    } else {
        [self performSelector:@selector(hide) withObject:nil afterDelay:0.2];
    }
    
}
- (void)hideCurrent// 在当前屏幕内消失
{
    if (_doubleTap) return;
    [_photoLoadingView removeFromSuperview];
    
    CGFloat duration = .20f;
    
    [UIView animateWithDuration:duration + .1 animations:^{
        self.contentOffset = CGPointZero;
        [_imageView setContentMode:UIViewContentModeScaleToFill];
        _imageView.frame = _photos.photo.rect;
        // gif图片显示第0张
        if (_imageView.image.images) {
            _imageView.image = _imageView.image.images[0];
        }
        // 可通知代理
        if ([self.photoViewDelegate respondsToSelector:@selector(photoViewSingleTap:)]) {
            [self.photoViewDelegate photoViewSingleTap:self];
        }
    } completion:^(BOOL finished) {
        
        // 通知代理
        if ([self.photoViewDelegate respondsToSelector:@selector(photoViewDidEndZoom:)]) {
            [self.photoViewDelegate photoViewDidEndZoom:self];
        }
    }];
}

- (void)hide
{
    if (_doubleTap) return;
    [_photoLoadingView removeFromSuperview];

    [UIView animateWithDuration:.5f animations:^{
        if (self.zoomScale == self.minimumZoomScale) {
            _imageView.transform = CGAffineTransformMakeScale(0.1, 0.1);
        } else {

        }
        _imageView.alpha = 0;
        
        if ([self.photoViewDelegate respondsToSelector:@selector(photoViewSingleTap:)]) {
            [self.photoViewDelegate photoViewSingleTap:self];
        }
    } completion:^(BOOL finished) {
        // 通知代理
        if ([self.photoViewDelegate respondsToSelector:@selector(photoViewDidEndZoom:)]) {
            [self.photoViewDelegate photoViewDidEndZoom:self];
        }
    }];
}

- (void)handleDoubleTap:(UIGestureRecognizer *)tap // 双击处理
{
    _doubleTap = YES;
    
    CGPoint touchPoint = [tap locationInView:self]; // 点击位置
    if (self.zoomScale == self.maximumZoomScale) {
        
        [self setZoomScale:self.minimumZoomScale animated:YES];
    } else {
        [self zoomToRect:CGRectMake(touchPoint.x, touchPoint.y, 1, 1) animated:YES];
    }
}
@end
